package com.zr.andealib.util;


import com.rfid.api.ADReaderInterface;
import com.rfid.api.GFunction;
import com.rfid.api.ISO14443AInterface;
import com.rfid.api.ISO14443ATag;
import com.rfid.api.ISO15693Interface;
import com.rfid.api.ISO15693Tag;
import com.rfid.def.ApiErrDefinition;
import com.rfid.def.RfidDef;
import com.zr.andealib.util.constant.AndeaConstant;
import com.zr.andealib.util.model.InventoryReport;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

/**
 * @author WQJ
 * @create 2019/11/19
 * @desc:读卡器操作类
 */
public class CardReaderUtil {

    private static ADReaderInterface m_reader2 = new ADReaderInterface();
    private static List<InventoryReport> inventoryList2 = new ArrayList<InventoryReport>();
    private static final int INVENTORY_USER = 3;


    private static boolean isInitSuccuse = true;

    private static Timer timer;

    public static void init() {
        OpenDev2();
        try {
            timer = new Timer();
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    byte[] useAnt = {1, 2, 3, 4, 5, 6, 7, 8};
                    if (inventoryTags2(useAnt)) {
                        String str = "";
                        if (inventoryList2.size() > 0) {
                            str = inventoryList2.get(0).getUidStr();
                            EventBus.getDefault().post(new HardEvent(str,  AndeaConstant.CALL_VERIFICATION_SUCCSES));
                            //关闭轮询
                            this.cancel();
                        }
                    }
                }
            }, 100, 200);
        } catch (Exception e) {
            EventBus.getDefault().post(new HardEvent("读卡器异常", AndeaConstant.CALL_INIT_VERIFICATION_ERROR));
        }

    }


    private static void OpenDev2() {
        try {
            if(m_reader2.isReaderOpen()) {
                return;
            }
            String conStrPara2 = String
                    .format("RDType=RL8000;CommType=COM;ComPath=%s;Baund=%s;Frame=%s;Addr=255",AndeaConstant.CARD_TTY, "38400", "8E1");
            int openResult = m_reader2.RDR_Open(conStrPara2);
            if (openResult != ApiErrDefinition.NO_ERROR) {
                isInitSuccuse = false;
                EventBus.getDefault().post(new HardEvent("初始化读卡器失败", AndeaConstant.CALL_INIT_VERIFICATION_ERROR));
            }
        } catch (Exception e) {
               EventBus.getDefault().post(new HardEvent("初始化读卡器失败", AndeaConstant.CALL_INIT_VERIFICATION_ERROR));
        }

    }

    private static boolean inventoryTags2(byte[] useAnt) {
        if (m_reader2 == null) {
            return false;
        } else if (!m_reader2.isReaderOpen()) {
            return false;
        }
        byte newAI = RfidDef.AI_TYPE_NEW;
        Object hInvenParamSpecList = ADReaderInterface
                .RDR_CreateInvenParamSpecList();
        ISO15693Interface.ISO15693_CreateInvenParam(hInvenParamSpecList,
                (byte) 0, false, (byte) 0x00, (byte) 0);
        ISO14443AInterface.ISO14443A_CreateInvenParam(
                hInvenParamSpecList, (byte) 0);
        Vector<Object> tagsList = new Vector<Object>();
        int iret = ~ApiErrDefinition.NO_ERROR;

        iret = m_reader2.RDR_TagInventory(newAI, useAnt, 0,
                hInvenParamSpecList);
        if (iret == ApiErrDefinition.NO_ERROR) {
            Object tagReport = m_reader2
                    .RDR_GetTagDataReport(RfidDef.RFID_SEEK_FIRST);
            while (tagReport != null) {
                Object obj = tag15693_1443a(tagReport);
                if (obj != null) {
                    tagsList.add(obj);
                }
                tagReport = m_reader2
                        .RDR_GetTagDataReport(RfidDef.RFID_SEEK_NEXT);
            }
            inventoryList2.clear();
            for (Object t : tagsList) {
                String uidStr = null;
                int ant_id = 0;
                if (t instanceof ISO15693Tag) {
                    ISO15693Tag tagData = (ISO15693Tag) t;
                    uidStr = GFunction.encodeHexStr(tagData.uid);
                    ant_id = (int) tagData.ant_id;
                } else if (t instanceof ISO14443ATag) {
                    ISO14443ATag tagData = (ISO14443ATag) t;
                    uidStr = GFunction.encodeHexStr(tagData.uid);
                    ant_id = (int) tagData.ant_id;
                }
                if (uidStr != null) {
                    boolean bTagExist = false;
                    InventoryReport report = new InventoryReport(uidStr, "" + ant_id);
                    for (InventoryReport tag : inventoryList2) {
                        if (tag.getUidStr().equals(uidStr)) {
                            bTagExist = true;
                            break;
                        }
                    }
                    if (!bTagExist) {
                        inventoryList2.add(report);
                    }
                }
            }
            return true;
        }

        return false;
    }

    private static Object tag15693_1443a(Object tagReport) {
        ISO15693Tag ISO15693TagData = new ISO15693Tag();
        int iret = ISO15693Interface.ISO15693_ParseTagDataReport(
                tagReport, ISO15693TagData);
        if (iret == ApiErrDefinition.NO_ERROR) {
            return ISO15693TagData;
        }

        ISO14443ATag ISO14444ATagData = new ISO14443ATag();
        iret = ISO14443AInterface.ISO14443A_ParseTagDataReport(
                tagReport, ISO14444ATagData);
        if (iret == ApiErrDefinition.NO_ERROR) {
            return ISO14444ATagData;
        }
        return null;
    }

    public static void onDestory() {
        if (timer != null) {
            timer.cancel();
        }
        if (m_reader2 != null && isInitSuccuse) {
            m_reader2.RDR_CloseRFTransmitter();
        }

    }


}
